package com.itszt.manager.service.impl;

import com.itszt.common.ConstanKeys;
import com.itszt.common.EasyUITreeBean;
import com.itszt.common.PicUrlUtil;
import com.itszt.manager.dao.ContentDao;
import com.itszt.manager.service.ContentService;
import com.itszt.pojo.TbContent;
import com.itszt.pojo.TbContentCategory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@EnableCaching
public class ContentServiceImpl implements ContentService {

    @Resource
    private ContentDao contentDao;

    @Value("${nginx_server}")
    private String ngnixUrl;
    @Override
    public List<EasyUITreeBean> showContentTrees(String parentid) {

        List<TbContentCategory> tbContentCategories = contentDao.queryCatsByParID(parentid);
        List<EasyUITreeBean> easyUITreeBeans = new ArrayList<>();

        for (TbContentCategory tbContentCategory : tbContentCategories) {
            EasyUITreeBean easyUITreeBean = new EasyUITreeBean();
            easyUITreeBean.setId(tbContentCategory.getId());
            easyUITreeBean.setText(tbContentCategory.getName());
            easyUITreeBean.setState(tbContentCategory.getIsParent() ? EasyUITreeBean.STATE_CLOSED:EasyUITreeBean.STATE_OPEN);

            easyUITreeBeans.add(easyUITreeBean);
        }
        return easyUITreeBeans;
    }

    @Override
    public List<EasyUITreeBean> showContentTopCats() {
        return showContentTrees("0");
    }

    @Override
    @CacheEvict(cacheNames = ConstanKeys.REDIS_CONTENT_MANAGER,key = ConstanKeys.REDIS_CONTENT_KEY+"+#tbContent.categoryId")
    public boolean saveContent(TbContent tbContent) {

        try {
            String pic1 = PicUrlUtil.genGroupPath(tbContent.getPic(), ngnixUrl);
            String pic2 = PicUrlUtil.genGroupPath(tbContent.getPic2(), ngnixUrl);

            tbContent.setPic(pic1);
            tbContent.setPic2(pic2);
            tbContent.setCreated(new Date());
            tbContent.setUpdated(new Date());
            contentDao.insertContent(tbContent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    @Cacheable(cacheNames = ConstanKeys.REDIS_CONTENT_MANAGER,key = ConstanKeys.REDIS_CONTENT_KEY+"+'89'")
    public List<TbContent> getBigAdv() {

        List<TbContent> tbContents = contentDao.queryContentByCid("89");

        return tbContents;
    }
}
